// pages/api/user/login.ts
import { NextApiRequest, NextApiResponse } from 'next';
import jwt from 'jsonwebtoken';
import redis from '../../../lib/redisClient';
import prisma from '../../../lib/prisma';

interface JwtPayload {
  id: string;
  userId: string;
}

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const { userId, password }: { userId: string; password: string } = req.body;

    try {
      const user = await prisma.user.findFirst({ where: { userId, password } });

      if (user) {
        const token = jwt.sign({ id: user.id.toString(), userId: user.userId }, process.env.JWT_SECRET as string, { expiresIn: '1h' });

        // 将 token 存入 Redis，设置 10 小时过期时间
        await redis.set(`token:${user.id}`, token, 'EX', 36000);

        return res.status(200).json({ token });
      } else {
        return res.status(401).json({ message: '账号或密码错误' });
      }
    } catch (error) {
      console.error('数据库查询错误:', error);
      return res.status(500).json({ message: '内部服务器错误' });
    }
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`不允许的方法: ${req.method}`);
  }
}
